package org.budo.mail;

import org.budo.mail.util.MailAddressUtil;
import org.budo.support.lang.util.StringUtil;
import org.springframework.util.Assert;

import _.mail.MailReceiver;
import b.async.Handler;
import lombok.Getter;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
public class AbstractMailReceiver implements MailReceiver {
    private String protocol;

    private Integer port;

    private String host;

    private String username;

    private String password;

    private Boolean ssl = false;

    public String getProtocol() {
        return null != protocol ? protocol : ((null != getHost() && getHost().startsWith("pop")) ? "pop3" : "imap");
    }

    public Integer getPort() {
        return null != port ? port : ((null != getProtocol() && StringUtil.equalsIgnoreCase("pop3", getProtocol())) ? 995 : 143);
    }

    public String getHost() {
        if (null != this.host) {
            return this.host;
        }

        Assert.hasText(this.getUsername(), "#48 username can not be null");
        return MailAddressUtil.guessReceiveHost(this.getUsername());
    }

    public String getUsername() {
        return null == this.username ? "" : this.username;
    }

    public void receive(Handler handler) {
        throw new RuntimeException("未实现, this=" + this);
    }

    public String toString() {
        return super.toString() //
                + "[protocol=" + this.getProtocol() //
                + ", host=" + this.getHost() //
                + ", port=" + this.getPort() //
                + ", username=" + this.getUsername() //
                + ", ssl=" + this.getSsl() + "]";
    }
}